package meb

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"os"
	"strings"
	"vitepress-serve/internal/common/hgin"
	"vitepress-serve/internal/model"
)

// 根据文件后缀声明内容类型
var declareContentType = map[string]string{
	".html": "text/html; charset=utf-8",
	".js":   "application/javascript",
	".css":  "text/css",
	".svg":  "image/svg+xml",
}

// HandlerStaticServer 静态文件服务
func (ctl *Controller) HandlerStaticServer(ctx *gin.Context) {
	path := ctx.Request.URL.Path
	if strings.HasSuffix(path, "/") {
		path += "/index.html"
	}
	dir := "/usr/www" // TODO 计划改为从启动参数或者环境变量读取
	fBytes, err := os.ReadFile(dir + path)
	if err != nil {
		http.NotFound(ctx.Writer, ctx.Request)
		return
	}
	// 请求文件后缀
	suffix := (strings.Split(path, "?")[0])[strings.LastIndex(path, "."):]
	if suffix == ".html" || suffix == ".js" {
		//登录会话
		token, _ := hgin.GetCookieToken(ctx)
		//未开会员,替换内容为空标签
		if token.Type != string(model.USER_TYPE_VIP) {
			var (
				tag     = "mosong-vip-content" //<div id="mosong-vip-content-beg"></div> Markdown <div id="mosong-vip-content-end"></div>
				beg     = tag + "-beg"
				end     = tag + "-end"
				content = string(fBytes)
			)
			if strings.Contains(content, beg) && strings.Contains(content, end) {
				fBytes = []byte(content[0:strings.Index(content, beg)] + tag + content[strings.Index(content, end)+len(end):])
			}
		}
	}
	// 根据文件取Content-Type
	contentType := declareContentType[suffix]
	if contentType == "" {
		contentType = http.DetectContentType(fBytes) //根据内容取Content-Type，优先使用自己声明的
	}
	ctx.Data(http.StatusOK, contentType, fBytes)
}
